import React, { useEffect, useState } from 'react'
import instance from '../../api/request'
import { Button, Space, Table, Tag } from 'antd';
import { Modal } from 'antd';
import {  Checkbox, Form, Input,message, Popconfirm ,Drawer } from 'antd';
function Index() {
  
  // 删除
const confirm = id => {
  console.log(id);
  message.success('删除成功');
  const shanchu=list.filter((v)=>v.id!=id)
  setList(shanchu)
};
const cancel = e => {
  console.log(e);
  message.error('Click on No');
};
  // 重置
    const [form] = Form.useForm();
  const cz=()=>{
   form.resetFields('')
  }
// 搜索
const [keyword,setkeyword]=useState('')
const Finish = values => {
  console.log('Success:', values);
  setkeyword(values.keyword)
};
const FinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
// 编辑
const [title,setTitle]=useState()
const [edit,setEdit]=useState()
const bian=(record)=>{
       setIsModalOpen(true);
       setTitle('编辑')
       setEdit(record.id)
    addform.setFieldsValue({
      title:record.title,
      content:record.content
    })
}
  // 新增
     const [addform] = Form.useForm();
    const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
    setTitle('新增')
    addform.resetFields()
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
const onFinish = values => {
  console.log('Success:', values);
 const  commData={
    title:values.title,//文章标题
content:values.content,//文章内容
tagList:values.tagList,//标签  array[string]
categoryList:values.categoryList,//分类  array[string]
authorId:47529555//用户id 暂时写死47529555 登陆成功后返回的用户信息
  }
  if(title=='新增'){
instance.post('/article',commData,{
    headers : {
  Authorization:'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA',
}
  }).then((res)=>{
    console.log(res);
   alert('新增成功')
   setIsModalOpen(false);
     getData()
  })
  }else{
    instance.put(`/article/${edit}`,commData,{
       headers : {
  Authorization:'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6Imp5a2wiLCJ1c2VySWQiOjQ3NTI5NTU1LCJyb2xlIjoxLCJpYXQiOjE3Mzk3OTQyNDIsImV4cCI6MTc0MjM4NjI0Mn0.O7KlsogMjr6YowtOXKGrEaldz5kjKHWQCn3FGvRd1bA',
}
    }).then((res)=>{
 alert('编辑成功')
   setIsModalOpen(false);
     getData()
    })
  }
  
};
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
  // 渲染列表
  const [list,setList]=useState()
  const getData=()=>{
    instance.get('/article/list',{params:{
      keyword
    }}).then((res)=>{
    setList(res.data.rows)
    })
  }
  useEffect(()=>{
    getData()
  },[keyword])
  // 数据
  const columns = [
  {
    title: 'Id',
    dataIndex: 'id',
    key: 'id',
    render: text => <a>{text}</a>,
  },
  {
    title: '文章标题',
    dataIndex: 'title',
    key: 'title',
  },
  {
    title: '文章内容',
    dataIndex: 'content',
    key: 'content',
  },
    {
    title: '发布时间',
    dataIndex: 'createdAt',
    key: 'createdAt',
  },
   {
    title: '更新时间',
    dataIndex: 'updatedAt',
    key: 'updatedAt',
  },
    {
    title: '阅读数量',
    dataIndex: 'viewCount',
    key: 'viewCount',
  },

  {
    title: 'Action',
    key: 'action',
    render: (_, record) => (
      <Space size="middle">
       <Button onClick={()=>bian(record)}>编辑</Button>
        <Popconfirm
    title="Delete the task"
    description="你确定删除吗？"
    onConfirm={()=>confirm(record.id)}
    onCancel={cancel}
    okText="确认删除"
    cancelText="取消"
  >
    <Button danger>删除</Button>
  </Popconfirm>
      </Space>
    ),
  },
];
  return (
    <div>
      {/* 搜索 */}
      <Form
      form={form}
      layout='inline'
    name="basic"
   
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={Finish}
    onFinishFailed={FinishFailed}
    autoComplete="off"
  >
    <Form.Item
      label="文章"
      name="keyword"
    >
      <Input />
    </Form.Item>

    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        搜索
      </Button>
       <Button type="primary" htmlType="submit" onClick={()=>cz()}>
        重置
      </Button>
    </Form.Item>
  </Form>
      {/* 新增 */}
      <Button type="primary" htmlType="submit" style={{float:"right",}} onClick={()=>showModal()}>添加</Button>
       <Modal
       form={addform}
        title="Basic Modal"
        closable={{ 'aria-label': 'Custom Close Button' }}
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
       <Form
       form={addform}
    name="basic"
    labelCol={{ span: 8 }}
    wrapperCol={{ span: 16 }}
    style={{ maxWidth: 600 }}
    initialValues={{ remember: true }}
    onFinish={onFinish}
    onFinishFailed={onFinishFailed}
    autoComplete="off"
  >
    <Form.Item
      label="文章标题"
      name="title"
      rules={[{ required: true, message: 'Please input your username!' }]}
    >
      <Input />
    </Form.Item>

    <Form.Item
      label="文章内容"
      name="content"
      rules={[{ required: true, message: 'Please input your password!' }]}
    >
      <Input/>
    </Form.Item>

    <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        确定
      </Button>
    </Form.Item>
  </Form>
      </Modal>
      <Table rowKey="id" columns={columns} dataSource={list}
      pagination={{
         total:85,
    showSizeChanger:true,
    showQuickJumper:true,
    // 31.为消息列表实现分页，每页 10 条，默认第一页。
    defaultPageSize:10,
    showTotal:total => `Total ${total} items`
      }}
      />;
    </div>
  )
}

export default Index